package com.fingard.dsp.bank.directbank.icbc02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IWithhold;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

/**
 * 工商银行单笔（全额、差额）代扣
 * @date 2020-05-08
 */
public class ICBC02Withhold extends ICBC02Base implements IWithhold {

    /**
     * 单笔差额代扣提交
     * @param p_req9208 单笔代扣请求对象
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_9208_singlePay(ReqBatPayRec p_req9208) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9208.reqHeader);
        try{
            bnkPackageID = p_req9208.reqBatchNO;
            bnkfSeqno = p_req9208.reqBatchNO;
            boolean hasOtherBk = p_req9208.hasOtherBank();
            boolean isSameSpd = p_req9208.isSamePaySpd();
            bnkTransCode = "PERDIS";// 批扣个人指令提交
            XmlTextWriter xmlWriter = new XmlTextWriter();
            // ------------ /CMS/eb/pub/ 开始------------
            writeCommonHeader(xmlWriter);
            // ------------ /CMS/eb/pub/ 结束------------
            // ------------ /CMS/eb/in/ 开始------------
            xmlWriter.writeElementString("OnlBatF", "1");
            if (hasOtherBk || !isSameSpd) {
                // 有跨行，或者普通加急标志不一样，只能逐笔入账
                xmlWriter.writeElementString("SettleMode", "0");
            } else {
                String settleMode1988 = getBankConfig().getValueAsString("settleMode9188","2");
                xmlWriter.writeElementString("SettleMode", settleMode1988);
            }
            xmlWriter.writeElementString("RecAccNo", p_req9208.ownAct);
            xmlWriter.writeElementString("RecAccNameCN", p_req9208.ownActName);
            xmlWriter.writeElementString("RecAccNameEN", "");
            xmlWriter.writeElementString("TotalNum", p_req9208.totalNum);
            xmlWriter.writeElementString("TotalAmt", StringHelper.amountMultiply100(p_req9208.totalAmt));
            xmlWriter.writeElementString("SignTime", Format.DateTime17Format.format(new Date()));
            xmlWriter.writeElementString("ReqReserved1", "");// p_req9188.abstractATS);
            xmlWriter.writeElementString("ReqReserved2", "");// p_req9188.reqBatchNO);
            // ------------ /CMS/eb/in/ 结束------------
            // ------------ /CMS/eb/in/rd/ 开始------------
            int tmpRdCount = 0;
            while (p_req9208.readRecord()) {
                //9208接口定义与9188接口定义存在差异，为了兼容
                p_req9208.readedDetail.payAct=p_req9208.readedDetail.recAct;
                p_req9208.readedDetail.payName=p_req9208.readedDetail.recName;
                p_req9208.readedDetail.payBankName=p_req9208.readedDetail.recBankName;
                p_req9208.readedDetail.payBankCode=p_req9208.readedDetail.recBankCode;
                p_req9208.readedDetail.payCur=p_req9208.readedDetail.recCur;
                p_req9208.readedDetail.recAct=p_req9208.ownAct;

                tmpRdCount++;
                XElement tmpXElement = convertRecDetailToBankXElement(p_req9208.readedDetail, tmpRdCount);
                xmlWriter.writeXElement(tmpXElement);
            }
            // ------------ /CMS/eb/in/rd/ 结束------------
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), true);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpRetCode + "-" + tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                        retAts.transState = tmpRetCode;
                        retAts.payInfoCode = tmpRetCode;
                        String reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
                        if (StringHelper.hasAnyChar(reqSeqID)) {
                            retAts.reqSeqID = reqSeqID;
                        } else {
                            retAts.reqSeqID = p_req9208.reqBatchNO;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "/CMS/eb/pub/RetCode节点为空";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.reqSeqID = p_req9208.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            e.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            WriteBankLogLn(e);
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 单笔差额代扣状态查询
     * @param p_req9244
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_9244_QrySinglePay(ReqQryBatPayRec p_req9244) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9244.reqHeader);
        retAts.reqSeqID = p_req9244.reqBatchNO;
        try {
            bnkPackageID = p_req9244.reqHeader.transSeqID;
            bnkTransCode = "QPERDIS";// 批量扣个人指令查询
            bnkfSeqno = bnkPackageID;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter);
            xmlWriter.writeElementString("QryfSeqno", p_req9244.reqBatchNO);
            xmlWriter.writeElementClosed("QrySerialNo");
            xmlWriter.writeElementClosed("ReqReserved1");
            xmlWriter.writeElementClosed("ReqReserved2");
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        if (tmpRetCode.equals("0") || tmpRetCode.equals("B0116") || tmpRetCode.equals("00000") || "B0098".equals(tmpRetCode) || "B0097".equals(tmpRetCode)) {
                            retAts.respCode = "0";
                            retAts.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/out/QryfSeqno");
                            if ("B0116".equals(tmpRetCode) || "B0098".equals(tmpRetCode) || "B0097".equals(tmpRetCode)) {
                                if (canBeNotExist(p_req9244, retAts, 70)) {
                                    retAts.respInfo = tmpRetMsg;
                                    if (StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
                                        retAts.reqSeqID = p_req9244.reqBatchNO;
                                    }
                                    retAts.transState = tmpRetCode;
                                    retAts.payInfoCode = tmpRetCode;
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.transState = "";
                                }
                            }
                            while (tmpBkReader.read("/CMS/eb/out/rd")) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                tmpRetDetail.payName = tmpBkReader.readedXElement.getSingleText("PayAccNameCN");
                                tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("PayAccNo");
                                tmpRetDetail.payAmount = StringHelper.amountDivide100(tmpBkReader.readedXElement.getSingleText("PayAmt"));
                                tmpRetDetail.curType = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CurrType"));
                                tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("UseCN");
                                tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("PostScript");
                                tmpRetDetail.result = tmpRetCode + "+" + tmpBkReader.readedXElement.getSingleText("Result");
                                tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("iRetCode");
                                String repReserved4=tmpBkReader.readedXElement.getSingleText("RepReserved4");
                                if(StringHelper.hasAnyChar(repReserved4) && repReserved4.contains("|")){
                                    String[] repReservedArr=repReserved4.split("\\|");
                                    if(repReservedArr.length>1){
                                        tmpRetDetail.successAmount = StringHelper.amountDivide100(repReservedArr[1]);
                                    }
                                }
                                String iRetMsg = tmpBkReader.readedXElement.getSingleTextNotNull("iRetMsg");
                                iRetMsg = iRetMsg.length() == 0 ? " " : iRetMsg;
                                String BankRem = tmpBkReader.readedXElement.getSingleTextNotNull("BankRem");
                                tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("iRetCode") + "-" + iRetMsg + "-" + BankRem;

                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpRetMsg;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "节点/CMS/eb/pub/RetCode为空";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            e.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            WriteBankLogLn(e);
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req9244.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}
